package com.smart.upload.control;

import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.smart.mvc.model.Result;
import com.smart.upload.bean.FileInfo;
import com.smart.upload.service.UploadService;

/**
 * <b>Description:文件上传</b><br>
 * @author 唐海洋
 * @version 1.0 2016-9-25 下午2:53:10
 */
@Controller
@RequestMapping("/upload")
public class UploadControl {
	
	@Resource private UploadService uploadService=null;
	
	@RequestMapping(value="/upload",method = RequestMethod.POST)
	public @ResponseBody Result upload(HttpServletRequest request,HttpServletResponse response) {
		
		Result r=null;
		try{
			 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
		        //判断 request 是否有文件上传,即多部分请求  
		        if(multipartResolver.isMultipart(request)){  
		            //转换成多部分request    
		            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
		            //取得request中的所有文件名  
		            Iterator<String> iter = multiRequest.getFileNames();  
		            if(!iter.hasNext()){
		            	r=Result.createErrorResult().setMessage("请选择要上传的文件");
		            }else{
		            	while(iter.hasNext()){  
		            		//取得上传文件  
		            		CommonsMultipartFile file = (CommonsMultipartFile) multiRequest.getFile(iter.next());  
		            		if(file != null){  
		        				FileInfo fileInfo=uploadService.save(((DiskFileItem)file.getFileItem()).getStoreLocation(), file.getOriginalFilename());
		        				r=Result.createSuccessResult().setData(fileInfo);
		            		}  
		            	}  
		            }  
		        }
		}catch (Exception e) {
			r=Result.createErrorResult().setMessage(e.getMessage());
		}
        return r;
	}
	
}